package cn.itlaobing.springbootdemo.web.controller;

import cn.itlaobing.springbootdemo.Constants;
import cn.itlaobing.springbootdemo.entity.SystemAccount;
import cn.itlaobing.springbootdemo.service.SystemAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class AuthenticationController extends BaseController {


    @Autowired
    private SystemAccountService systemAccountService;
    @GetMapping("/signin")
    public String signin(){
        return "/signin";
    }

    @PostMapping("/signin")
    public String signin(String account, String password, Model model, HttpServletRequest request){
        //验证登录，登录成功放入session，否则返回
        boolean hasError=false;
        if(StringUtils.isEmpty(account)){
            model.addAttribute("error","用户名不能为空");
            hasError=true;
        }        if(StringUtils.isEmpty(account)){
            model.addAttribute("error","用户名不能为空");
            hasError=true;
        }
        if(StringUtils.isEmpty(password)){
            model.addAttribute("error","用户名不能为空");
            hasError=true;
        }
        if(hasError){
            return "/signin";
        }


        SystemAccount systemAccount=systemAccountService.authentication(account,password);
        if(systemAccount==null){
            model.addAttribute("error","用户名或者密码不正确");
            return "/signin";
        }
        //登录成功
        request.getSession().setAttribute(Constants.CURRENT_ACCOUNT,systemAccount);
        return "redirect:/";
    }


    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().invalidate(); //让session失效
        return "redirect:/signin";
    }

}
